package com.uci.photogam.facebook;

import org.json.JSONArray;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.uci.photogam.ActivityCamera;
import com.uci.photogam.ActivityEditImage;
import com.uci.photogam.ActivityShare;
import com.uci.photogam.AdapterMainMenu;
import com.uci.photogam.DeviceListActivity;
import com.uci.photogam.R;
import com.uci.photogam.V;

public class FacebookSSOActivity extends Activity{

	//private Handler mHandler;
	protected static JSONArray jsonArray;
	private GridView gridview;
	private final String[] texts = {"Login", "Photo Albums", "Logout" };
	private final static int login = 0;
	private final static int albums = 1;
	private final static int logout = 2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fb_login);
		if(Utility.mFacebook == null)
			Utility.mFacebook = new Facebook("393520284025644");
		if(Utility.mAsyncRunner == null)
			Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
		//mHandler = new Handler();

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		gridview = (GridView) findViewById(R.id.fb_logout_album_gridview);
		gridview.setColumnWidth(metrics.widthPixels / 2);
		gridview.setAdapter(new AdapterMainMenu(this, texts, metrics));
		gridview.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				switch(position){
				case login:
					//Authorize this app to access the user's photos
					if(!Utility.mFacebook.isSessionValid())
						Utility.mFacebook.authorize(FacebookSSOActivity.this, new String[]{"user_photos"}, new LogInDialogListener());	
					else
						V.toastMessage(getBaseContext(), "You are already logged in.");
					break;
				case albums:
					if(!Utility.mFacebook.isSessionValid())
						V.toastMessage(getBaseContext(), "You must log in first.");
					else
						Utility.mAsyncRunner.request("me/albums", new AlbumRequestListener());
					break;
				case logout:
					if(!Utility.mFacebook.isSessionValid())
						V.toastMessage(getBaseContext(), "You must log in first.");
					else
						Utility.mAsyncRunner.logout(getBaseContext(), new BaseRequestListener() {
							public void onComplete(String response, Object state) {
								//VarsPhotoGam.toastMessage(getBaseContext(), "You have logged out.");
							}
						});
					break;
				}
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
		if(resultCode == RESULT_OK && requestCode == V.REQ_CODE_PICK_PICTURE_FB)
		{
			FacebookSSOActivity.this.setResult(RESULT_OK, data);
			
			Intent i = new Intent(FacebookSSOActivity.this, ActivityEditImage.class);
			Bundle bundle = data.getExtras();
			Bitmap image = (Bitmap) bundle.get("image");
			i.putExtra(V.TAKEN_PICTURE, false);
			i.putExtra(V.IMAGE_PATH, bundle.getString("imgUrl"));
			i.putExtra(V.IMAGE_FILE, "");
			startActivity(i);
		}

	}

	public void onResume() {    
		super.onResume();
		Utility.mFacebook.extendAccessTokenIfNeeded(this, null);
	}

	/**
	 * After logging in, request the albums from facebook
	 * @author Alexis
	 *
	 */
	class LogInDialogListener extends BaseDialogListener{

		public void onComplete(Bundle values) {
			//Utility.mAsyncRunner.request("me/albums", new AlbumRequestListener());
			V.toastMessage(getBaseContext(), "You have logged in.");
		}
	}

	/**
	 * On completion of getting the albums, send the api response to FacebookAlbumGallery
	 * @author Alexis
	 *
	 */
	class AlbumRequestListener extends BaseRequestListener{

		public void onComplete(String response, Object state) {
			Intent intent = new Intent(getApplicationContext(), FacebookAlbumList.class);
			intent.putExtra("API_RESPONSE", response);
			startActivityForResult(intent, V.REQ_CODE_PICK_PICTURE_FB);
		}
	}
}

